﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TAS.XtOM.Tutorial.Web.Models.LinkedIn.oAuth;
using TAS.XtOM.Tutorial.Web.Models.LinkedIn;


namespace TAS.XtOM.Tutorial.Web.Controllers
{
	[HandleError]
	public class HomeController : Controller
	{
		private oAuthLinkedIn LIoAuth = new oAuthLinkedIn();

		public ActionResult Index()
		{
			// Check to save access token for linked in
			string token = Request.QueryString["oauth_token"];
			string verifier = Request.QueryString["oauth_verifier"];

			if (!string.IsNullOrEmpty(token) && !string.IsNullOrEmpty(verifier))
			{
				SaveAccessToken(token, verifier);
				return RedirectToAction("LinkedInProfileView");
			}

			if (IsLIConnected)
				return View();
			else
				return View();
		}

		public ActionResult LinkedInProfileView()
		{
			return View(LoadLinkedInData());
		}

		public ActionResult LIConnect()
		{
			string authLink = LIoAuth.AuthorizationLinkGet();
			Session["LIToken"] = LIoAuth.Token;
			Session["LITokenSecret"] = LIoAuth.TokenSecret;

			return Redirect(authLink);
		}

		private void SaveAccessToken(string token, string verifier)
		{
			LIoAuth.Token = token;
			LIoAuth.TokenSecret = Session["LITokenSecret"] as string;
			LIoAuth.Verifier = verifier;

			LIoAuth.AccessTokenGet(token);

			Session["LIToken"] = LIoAuth.Token;
			Session["LITokenSecret"] = LIoAuth.TokenSecret;
			Session["LiVerifier"] = LIoAuth.Verifier;
		}

		private LIPerson LoadLinkedInData()
		{
			oAuthLinkedIn LIoAuth = new oAuthLinkedIn();
			LIoAuth.Token = Session["LIToken"] as string;
			LIoAuth.TokenSecret = Session["LITokenSecret"] as string;
			LIoAuth.Verifier = Session["LiVerifier"] as string;

			string response = LIoAuth.APIWebRequest("GET", "http://api.linkedin.com/v1/people/~:(id,first-name,last-name,headline,location:(name,country),industry,current-status,current-status-timestamp,num-connections,summary,specialties,interests,positions,educations,recommendations-received,date-of-birth,main-address,member-url-resources,picture-url,phone-numbers)", null);
			LIPerson linkedInPerson = new LIPerson();
			linkedInPerson.MapXmlData(response);
			return linkedInPerson;
		}

		private bool IsLIConnected
		{
			get
			{
				if (string.IsNullOrEmpty(Session["LIToken"] as string) || string.IsNullOrEmpty(Session["LITokenSecret"] as string) || string.IsNullOrEmpty(Session["LIVerifier"] as string))
					return false;
				return true;
			}
		}
	}
}
